package lew.bing.exp.lock;

import java.time.LocalDateTime;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by 刘国兵 on 2018/8/5.
 */
public class TestSpinLock {

    static class SpinLock {
        private AtomicReference<Thread> owner = new AtomicReference<>();
        private int count = 0;

        public void lock() {
            Thread current = Thread.currentThread();
            if (current == owner.get()) {
                count ++;
                return;
            }
            while(!owner.compareAndSet(null, current)){// 通过cas操作来判断是否获取锁
            }
        }
        public void unlock (){
            Thread current = Thread.currentThread();
            if (current == owner.get()) {
                if (count != 0) {
                    count --;
                }else {
                    owner.compareAndSet(current, null);// 释放锁
                }
            }
        }
    }

    public static void main(String[] args) {
        SpinLock spinLock = new SpinLock();
        new Thread(new Runnable() {
            @Override
            public void run() {
                spinLock.lock();
                System.out.println(Thread.currentThread().getName() + "获得了锁:"+ LocalDateTime.now());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                spinLock.unlock();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                spinLock.lock();
                System.out.println(Thread.currentThread().getName() + "获得了锁"+ LocalDateTime.now());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                spinLock.unlock();
            }
        }).start();

        System.out.println("按任意键退出测试");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        System.out.println("正在退出");
    }


}
